package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.service.PerencanaanRPCService;
import id.net.iconpln.bb.client.service.PerencanaanRPCServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonGroup;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbRencanaProduksi extends LayoutContainer {
	private final PerencanaanRPCServiceAsync service = GWT.create(PerencanaanRPCService.class);
	private FormBinding formBindings;  
	private FormData formData; 
	private Grid gridPltu, gridUraian,gridRkap;
	private ComboBox cboBulan,cboTahun,cboUnit;
	private ListStore storePltu,storeUraian, storeTahun,storeUnit,storeBulan;
	private GroupingStore storeRkap;
	private Button bNew,btnTambah,btnLoad, btnReload;
	private TextField tNoRkap,namaPltu;
	private ColumnModel cm;
	private TextField<String> text,noRkap;
	private Date today = new Date();	
	private DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy");
	private NumberFormat number = NumberFormat.getFormat("###.###"); 
	private String dt,cf,sfc,jp;
	
	@Override
	  protected void onRender(Element parent, int pos) {
	    super.onRender(parent, pos); 
	    setLayout(new FitLayout());   
	    String mdl = Registry.get("isModule");
	    initStore();
	    
	    formData = new FormData("-20"); 
	    ContentPanel cp = new ContentPanel();  
	   
	    cp.setHeaderVisible(false);
	    cp.setFrame(true);  
	    cp.setSize(900, 400);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL)); 
 
	    rkap("rencana","LISTRENC");
	    rkap("master","TAHUN");
	    rkap("master","BULAN");
//	    rkap("master","UNIT");
	    
	    gridPltu = createGridPltu();  
//	    gridPltu.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
//	    gridPltu.getSelectionModel().addListener(Events.SelectionChange,  
//	        new Listener<SelectionChangedEvent<BaseModel>>() {  
//	          public void handleEvent(SelectionChangedEvent<BaseModel> be) {
//	            if (be.getSelection().size() > 0) {  	              
//	              formBindings.bind((ModelData) be.getSelection().get(0));  
//	            } else {  
//	              formBindings.unbind();  
//	            }  
//	          }  
//	        });
	    
	    ToolBar gridPltuTitle = new ToolBar();
	    gridPltuTitle.add(new LabelToolItem("<b>Data Pembangkit</b>"));
	    gridPltuTitle.add(new SeparatorToolItem());
	    
	    ContentPanel pnlPltu = new ContentPanel();
	    pnlPltu.setHeaderVisible(false);
	    pnlPltu.setLayout(new RowLayout(Orientation.HORIZONTAL));
	    pnlPltu.add(gridPltu,new RowData(1, 1));
	    pnlPltu.setTopComponent(gridPltuTitle);
	    
	    gridUraian = createGridUraian();
	    
	    ToolBar gridUraianTitle = new ToolBar();
//	    gridUraianTitle.add(new LabelToolItem("<b>Entry RKAP</b>"));
//	    gridUraianTitle.add(new SeparatorToolItem());
//
//	    gridUraianTitle.add(cboUnit);  
//	    gridUraianTitle.add(new SeparatorToolItem());  

	    ButtonGroup group = new ButtonGroup(2);  
	    group.setHeading("Entry Rencana Produksi & Kebutuhan");  
	    group.setWidth(150);

	    
	    group.add(new Button(" Tahun"));//, IconHelper.createStyle("icon-open")));
	    
	    cboTahun = new ComboBox();  
	    	cboTahun.setName("tahun");  
		//    cboBulan.setFieldLabel("Jetty / Dermaga");
		    cboTahun.setEmptyText("Tahun..");  
		    cboTahun.setDisplayField("tahun");  
		    cboTahun.setWidth(100);  
		    cboTahun.setStore(storeTahun);  
		    cboTahun.setTypeAhead(true);  
		    cboTahun.setEnabled(false);
		    cboTahun.setTriggerAction(TriggerAction.ALL);
		    cboTahun.addListener(Events.Select, new Listener<FieldEvent>() {
				@Override
				public void handleEvent(FieldEvent be) {
					// TODO Auto-generated method stub
//					MessageBox.alert("info", "Tahun " + fmt.format(today)  ,null);
					noRkap.setValue("");	
					Map mapParam = new FastMap();
//            		mapParam.put("tahun", fmt.format(today));
					mapParam.put("tahun", cboTahun.getRawValue().toString());
            		mapParam.put("id_pltu", Registry.get("id_pltu"));
            		  service.getListRencanaByKit("TAHUNRENCPRO", mapParam,new AsyncCallback<List<Map>>() {
            	  			public void onFailure(Throwable caught) {
            	  				GWT.log(caught.getMessage(), null);  			  				
            	  			}

            	  			public void onSuccess(List<Map> result) {
            	  				GWT.log(" " + Registry.get("id_pltu"), null);
//            	  					MessageBox.alert("info", "tahun " + result.get(0).get("tahun").toString() + " no rakp "  + result.get(0).get("no_rkap").toString() ,null);//            	  				
//            	  					noRkap.setValue(result.get(0).get("no_rkap").toString());	
            	  	  				storeRkap.removeAll();
            	  	  				storeRkap.add(ClientModule.setListBaseModelFromListMap(result));
            	  	  				gridRkap.unmask();	
            	  					if (result.size() <= 0){
            	  						bNew.setEnabled(true);
				    	  				cboBulan.setEnabled(false);
//				    	  				cboTahun.setEnabled(true);
				    	  				btnTambah.setEnabled(false);		
				    	  				cboUnit.setEnabled(false);

            	  					}else{
            	  						MessageBox.alert("info", "Ditemukan Data RKAP <br> Tahun " + result.get(0).get("tahun").toString() + " NO RKAP "  + result.get(0).get("no_rkap").toString() ,null);//            	  				
                	  					noRkap.setValue(result.get(0).get("no_rkap").toString());
                	  					bNew.setEnabled(false);
				    	  				cboBulan.setEnabled(true);
//				    	  				cboTahun.setEnabled(true);
				    	  				btnTambah.setEnabled(true);		
				    	  				cboUnit.setEnabled(true);

            	  					}		

            	  			}  			
            	  		});

					
//					} catch (ParseException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
					
				}

		    }); 	
//	    Button btn = new Button("", IconHelper.createStyle("add16"));  
		 group.add(cboTahun);
	    
	    Button btn = new Button("PLTU"); //, IconHelper.createStyle("icon-pln"));  
	    group.add(btn);
	    
	    namaPltu = new TextField<String>();
	    namaPltu.setReadOnly(true);
	    namaPltu.setWidth(180);
	    
	    group.add(namaPltu);
	    
//	    group.add(new SeparatorToolItem());  
  
	    
	    btn = new Button("No RKAP"); //, IconHelper.createStyle("icon-load"));  
//	    Menu menu = new Menu();  
//	    menu.add(new MenuItem("Copy me"));  
//	    btn.setMenu(menu);  
	    group.add(btn);
	    
	    noRkap = new TextField<String>();
	    noRkap.setReadOnly(true);
	    noRkap.setWidth(150);
	    group.add(noRkap);
	    
//	    btn = new Button("Copy", IconHelper.createStyle("add16"));  
//	    group.add(btn);  
//	  
//	    btn = new Button("Paste", IconHelper.createStyle("add16"));  
//	    group.add(btn);  
	    group.add(new SeparatorToolItem());
	    bNew = new Button("Submit",IconHelper.createStyle("icon-disk"));
//	    bNew.setWidth(50);
	    
	    bNew.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
//					
					
					Map mapParam = new FastMap();
					
					if (cboTahun.getRawValue().equals("") ){
						MessageBox.alert("Info", "Silahkan Pilih Pembangkit & Tahun RAKP", null);
					}else {
						if (noRkap.getRawValue().equals("")){
								mapParam.put("id_pltu", Registry.get("id_pltu").toString());
		//						mapParam.put("no_rkap", noRkap.getValue());
								mapParam.put("tahun", cboTahun.getRawValue());
					    		mapParam.put("createby", Registry.get("whoAmI").toString());
					    		mapParam.put("app_access", "WEB");
				   			    mapParam.put("crud", "RKAP");
				   			    
					    		Set set = mapParam.entrySet(); 
					    		Iterator i = set.iterator(); 
					    		while(i.hasNext()) { 
					    		Map.Entry me = (Map.Entry)i.next();
		//			    			MessageBox.alert(me.getKey()+"",": " + me.getValue(), null);
						    		GWT.log(me.getKey() + ": " + me.getValue()); 
					    		} 
		
								
						  		  service.crudPerencanaan("RKAP", mapParam,new AsyncCallback<List<Map>>() {
						    			public void onFailure(Throwable caught) {
						    				GWT.log(caught.getMessage(), null);  			  				
						    			}
			
						    			public void onSuccess(List<Map> result) {
						    				
						    					MessageBox.alert("Info", "NO RKAP :  " + result.get(0).get("message").toString().toString() ,null);
						    					noRkap.setValue(result.get(0).get("message").toString().substring(4));
		//				    	  				storeRkap.removeAll();
		//				    	  				storeRkap.add(ClientModule.setListBaseModelFromListMap(result));
		//				    	  				gridRkap.unmask();
						    	  				cboBulan.setEnabled(true);
						    	  				cboTahun.setEnabled(true);
						    	  				btnTambah.setEnabled(true);		
						    	  				cboUnit.setEnabled(true);
			
						    			}  			
						    		});
						}else{
							MessageBox.alert("Info","Silahkan Pilih Tahun Yang belum mempunyai NO RKAP", null);
						}
					}
			} 	
	     });
	    
	    group.add(bNew);  
	    
	    
	    gridUraianTitle.add(group);  
	  
	    ButtonGroup group2 = new ButtonGroup(2);  
//	    group2.setHeading("Other Bugus Actions");  
	  
			
//	    gridUraianTitle.add(cboTahun);  
//	    gridUraianTitle.add(new SeparatorToolItem());  

	    
	    btn = new Button("Bulan"); //, IconHelper.createStyle("add16"));  
	    btn.setWidth(80);
	    group2.add(btn);  
	    
	    cboBulan = new ComboBox();  
//	    cboBulan.setName("id_bulan");  
//    cboBulan.setFieldLabel("Jetty / Dermaga");
	    cboBulan.setEmptyText("Bulan..");  
	    cboBulan.setDisplayField("bulan");
//	    cboBulan.setValueField("id_bulan");
	    cboBulan.setWidth(120);  
	    cboBulan.setEnabled(false);
	    cboBulan.setStore(storeBulan);  
	    cboBulan.setTypeAhead(true);  
	    cboBulan.setTriggerAction(TriggerAction.ALL);
    
//    type.addListener(Events.Change, new Listener<FieldEvent>() {  
//      public void handleEvent(FieldEvent be) {  
//        boolean simple = type.getSimpleValue().equals("Simple");  
//        sm.deselectAll();  
//        sm.setSelectionMode(simple ? SelectionMode.SIMPLE : SelectionMode.MULTI);  
//      }  
//    });  
    	group2.add(cboBulan);  
	  
	    btn = new Button("Unit"); //, IconHelper.createStyle("add16"));  
	    btn.setWidth(80);
	    group2.add(btn);
	    
	    cboUnit = new ComboBox();  
//    cboJetty.setName("id_unit_jetty");  
//    cboBulan.setFieldLabel("Jetty / Dermaga");
	    cboUnit.setEmptyText("Unit..");  
	    cboUnit.setDisplayField("unit");  
	    cboUnit.setWidth(120);  
	    cboUnit.setStore(storeUnit);  
	    cboUnit.setTypeAhead(true);  
	    cboUnit.setEnabled(false);
	    cboUnit.setTriggerAction(TriggerAction.ALL);
	    cboUnit.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
			@Override
			public void selectionChanged(SelectionChangedEvent<ModelData> se) {
				// TODO Auto-generated method stub
					rkap("master","UNIT");    		
//					
					Map mapParams = new FastMap();
					mapParams.put("id_unit",cboUnit.getValue().get("id_unit").toString());
					mapParams.put("id_pltu", Registry.get("id_pltu").toString());
					mapParams.put("tahun", cboTahun.getRawValue());
					mapParams.put("no_rkap", noRkap.getRawValue().toString());


		    		Set set = mapParams.entrySet(); 
		    		Iterator i = set.iterator(); 
		    		while(i.hasNext()) { 
		    		Map.Entry me = (Map.Entry)i.next();
//			    			
			    		GWT.log(me.getKey() + ": " + me.getValue()); 
		    		} 
					
			  		  service.getListRencanaByKit("CEKUNIT", mapParams,new AsyncCallback<List<Map>>() {
			    			public void onFailure(Throwable caught) {
			    				GWT.log(caught.getMessage(), null);  			  				
			    			}

			    			public void onSuccess(List<Map> result) {
			    				
			    				int j = Integer.parseInt(result.get(0).get("jml").toString());
			    				
//			    				MessageBox.alert("info", "" + j, null);
			    				if (j <= 0){
			    					
			    					Map mapParams = new FastMap();

									mapParams.put("id_unit",cboUnit.getValue().get("id_unit").toString());
        							mapParams.put("id_pltu", Registry.get("id_pltu").toString());
        							mapParams.put("tahun", cboTahun.getRawValue());
        							mapParams.put("no_rkap", noRkap.getRawValue().toString());
        							mapParams.put("createby", Registry.get("whoAmI").toString());
        							mapParams.put("app_access", "WEB");
        							mapParams.put("crud", "CREATE");
									
							  		  service.crudPerencanaan("RKAP", mapParams,new AsyncCallback<List<Map>>() {
							    			public void onFailure(Throwable caught) {
							    				GWT.log(caught.getMessage(), null);  			  				
							    			}
				
							    			public void onSuccess(List<Map> result) {
							    				rkap("rencana","RKAP");
							    			}
							  		  });	
			    				}		
			    				
			    			}
			  		  });
			   } 
		    });

	    group2.add(cboUnit);
	  
	    btnLoad = new Button("Load", IconHelper.createStyle("icon-load"));
	    btnLoad.setWidth(80);
	    btnLoad.setVisible(false);
	    btnLoad.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
//				if (cboBulan.getRawValue().equals("") && cboUnit.getRawValue().equals("")){										
					MessageBox.alert("Info", "Mohon Dipilih Filter Bulan & Unit", null);	
//				}else{
					rkap("master","URAIAN");
//					MessageBox.alert("info", "Generate lanjutkan", null);
//				}
			} 	
	     });

	    group2.add(btnLoad);
	    
	    btnTambah = new Button("Tambah", IconHelper.createStyle("icon-add"));
	    btnTambah.setEnabled(false);
	    btnTambah.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(final ButtonEvent ce) {
				// TODO Auto-generated method stub
				if (cboBulan.getRawValue().equals("") && cboUnit.getRawValue().equals("")){										
					MessageBox.alert("Info", "Mohon Dipilih Filter Bulan & Unit", null);	
				}else{

					
            		Map mapParam = new FastMap();
            		mapParam.put("cf", cf);
            		mapParam.put("dt", dt);
            		mapParam.put("jp", jp);
            		mapParam.put("sfc", sfc);
            		
            		  service.getFormulaProduksi("",mapParam,new AsyncCallback<List<Map>>() {
            	  			public void onFailure(Throwable caught) {
            	  				GWT.log(caught.getMessage(), null);  			  				
            	  			}

            	  			public void onSuccess(List<Map> result) {
            	  				
            	  				String pk = number.format(Double.parseDouble(result.get(0).get("produksi").toString()));
            	  				String kb = number.format(Double.parseDouble(result.get(0).get("kebutuhan").toString()));	
//            	  					MessageBox.alert("info", "tahun " + result.get(0).get("tahun").toString() + " no rakp "  + result.get(0).get("no_rkap").toString() ,null);//
//            					Registry.get("dt") +" cf " + Registry.get("cf") + " jp " + Registry.get("cf") + " sfc " + Registry.get("sfc") + " totl batubara " + 
            					MessageBox.confirm("Info", " NO RKAP " + noRkap.getRawValue().toString() 
            							+ "<br> Bulan = " + cboBulan.getRawValue().toString()
//            							+ "<br> Bulan = " + cboBulan.getValue().get("bln").toString()
            							+ "<br> Unit = " + cboUnit.getRawValue().toString()
//            							+ "<br> ID UNIT= " + cboUnit.getValue().get("id_unit").toString()
//            							+ "<br> ID PLTU = " + Registry.get("id_pltu").toString()
            							+ "<br> Tahun = " + cboTahun.getRawValue().toString()
//            							+ "<br> Uraian = cf :" + cf + " dt :" + dt + " sfc :" + sfc + "jp : "+ jp
            							+" <br> Kebutuhan Batubara = " + kb 
            							+ "<br> Produksi Kwh = " + pk 
            							+" <br>" + "Apakah Anda Ingin Menyimpan ?",new Listener<MessageBoxEvent>() {

											@Override
											public void handleEvent(
													MessageBoxEvent be) {
												// TODO Auto-generated method stub
												Button btn = be.getButtonClicked();
												if (btn.getText().equals("Yes")){
													Map mapParams = new FastMap();

													mapParams.put("id_unit",cboUnit.getValue().get("id_unit").toString());
			            							mapParams.put("id_pltu", Registry.get("id_pltu").toString());
			            							mapParams.put("tahun", cboTahun.getRawValue());
			            							mapParams.put("no_rkap", noRkap.getRawValue().toString());
			            							mapParams.put("updateby", Registry.get("whoAmI").toString());
			            							mapParams.put("app_access", "WEB");
			            							mapParams.put("crud", "CREATE");
													
											  		  service.crudPerencanaan("RKAP", mapParams,new AsyncCallback<List<Map>>() {
											    			public void onFailure(Throwable caught) {
											    				GWT.log(caught.getMessage(), null);  			  				
											    			}
								
											    			public void onSuccess(List<Map> result) {
											    				
//											    					MessageBox.alert("Info", "NO RKAP :  " + noRkap.getRawValue().toString() + "Telah Berhasil Disimpan " ,null);
//											    					noRkap.setValue(result.get(0).get("message").toString().substring(4));
//											    	  				storeRkap.removeAll();
//											    	  				storeRkap.add(ClientModule.setListBaseModelFromListMap(result));
//											    	  				gridRkap.unmask();
								

																Map mapParam = new FastMap();
																			   			    									   			   
						            							mapParam.put("bulan",cboBulan.getValue().get("bln").toString());
						            							mapParam.put("id_unit",cboUnit.getValue().get("id_unit").toString());
						            							mapParam.put("id_pltu", Registry.get("id_pltu").toString());
						            							mapParam.put("tahun", cboTahun.getRawValue());
						            							mapParam.put("no_rkap", noRkap.getRawValue().toString());
						            							mapParam.put("cf",cf); 
						            							mapParam.put("dt",dt); 
						            							mapParam.put("sfc",sfc); 
						            							mapParam.put("jp",jp);
						            							mapParam.put("updateby", Registry.get("whoAmI").toString());
						            							mapParam.put("app_access", "WEB");
						            							mapParam.put("crud", "UPDATE");
//						            							
													    		Set set = mapParam.entrySet(); 
													    		Iterator i = set.iterator(); 
													    		while(i.hasNext()) { 
													    		Map.Entry me = (Map.Entry)i.next();
										//			    			MessageBox.alert(me.getKey()+"",": " + me.getValue(), null);
														    		GWT.log(me.getKey() + ": " + me.getValue()); 
													    		} 
																
																						
													  		  service.crudPerencanaan("RKAP", mapParam,new AsyncCallback<List<Map>>() {
													    			public void onFailure(Throwable caught) {
													    				GWT.log(caught.getMessage(), null);  			  				
													    			}
										
													    			public void onSuccess(List<Map> result) {
													    				
													    					MessageBox.alert("Info", "NO RKAP :  " + noRkap.getRawValue().toString() + "  Telah Berhasil Disimpan " ,null);
//													    					noRkap.setValue(result.get(0).get("message").toString().substring(4));
													    					rkap("rencana","RKAP");
//										
													    			}  			
													    		});
											    			}  			
											    		});


												}
//												else{
//													MessageBox.alert("info", "" + btn.getText() , null);
//												}
												
												
											}
            						
            					}
										 
            							
            					);

            	  			}  			
            	  		});

					
				}
			} 	
	     });
	    
	    group2.add(btnTambah);  
	  
	    gridUraianTitle.add(group2);  

	    
	    
	    ContentPanel pnlUraian = new ContentPanel();
	    pnlUraian.setHeaderVisible(false);
	    pnlUraian.setLayout(new RowLayout(Orientation.HORIZONTAL));
	    pnlUraian.add(gridUraian,new RowData(1, 1));
	    pnlUraian.setTopComponent(gridUraianTitle);
	    
	    
	    gridRkap = createGridRkap();
	    ToolBar gridRkapTitle = new ToolBar();
	    gridRkapTitle.add(new LabelToolItem("<b>Renc Prod & Kebutuan</b>"));
	    gridRkapTitle.add(new SeparatorToolItem());
	    btnReload = new Button("Reload",IconHelper.createStyle("icon-open"));
	    
	    btnReload.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				rkap("rencana","RKAP");
			}
	    	
	    });	

	    gridRkapTitle.add(btnReload);
	    
	    ContentPanel pnlRkap = new ContentPanel();
	    pnlRkap.setHeaderVisible(false);
	    pnlRkap.setLayout(new RowLayout(Orientation.HORIZONTAL));
	    pnlRkap.add(gridRkap,new RowData(1, 1));
	    pnlRkap.setTopComponent(gridRkapTitle);
	    	    	    
	    

	    ContentPanel pnlJoinPltuUraian = new ContentPanel();
	    pnlJoinPltuUraian.setHeaderVisible(false);
	    pnlJoinPltuUraian.setLayout(new RowLayout(Orientation.VERTICAL));	    	    
	    
	    if (mdl.equals("PERENCANAAN")){
		    pnlJoinPltuUraian.add(pnlPltu, new RowData(.99, .5));
		    pnlJoinPltuUraian.add(pnlUraian, new RowData(.99, .5));

	    }else{
		    pnlJoinPltuUraian.add(pnlPltu, new RowData(.99, 1));
	    }

	    
	    cp.add(pnlJoinPltuUraian, new RowData(.5, 1));
	    cp.add(pnlRkap, new	 RowData(.5, 1));
 
	    add(cp, new FitData(5));  
	  }
	private void rkap(String kode, final String codectrl) {
		// TODO Auto-generated method stub
		Map mapParam = new FastMap();
		if (codectrl.equals("UNIT")){
			mapParam.put("id_pltu", Registry.get("id_pltu").toString());
		}
		if (kode.equals("master")){			 
	  		  service.getMaster(codectrl, mapParam,new AsyncCallback<List<Map>>() {
	  			public void onFailure(Throwable caught) {
	  				GWT.log(caught.getMessage(), null);  			  				
	  			}

	  			public void onSuccess(List<Map> result) {
	  				 if (codectrl.equals("BULAN")){
	  	  				storeBulan.removeAll();
	  	  				storeBulan.add(ClientModule.setListBaseModelFromListMap(result));
	  				 }else if (codectrl.equals("TAHUN")){	 
	  	  			    storeTahun.removeAll();
	  				    storeTahun.add(ClientModule.setListBaseModelFromListMap(result));
	  				 }else if (codectrl.equals("UNIT")){	 
		  	  			    storeUnit.removeAll();
		  				    storeUnit.add(ClientModule.setListBaseModelFromListMap(result));
	  				 }else if (codectrl.equals("URAIAN")){	 
		  	  			    storeUraian.removeAll();
		  				    storeUraian.add(ClientModule.setListBaseModelFromListMap(result));	 
		  				    gridUraian.unmask();  
	  				 }	    
	  		     }  			
	  		});
		}else if (kode.equals("rencana")){
			if (codectrl.equals("RKAP")){
				mapParam.put("id_pltu", Registry.get("id_pltu").toString());
				if (cboTahun.getRawValue().equals("")){
					mapParam.put("tahun", fmt.format(today));					
				}else{
					mapParam.put("tahun", cboTahun.getRawValue().toString());
				}
			}else if (codectrl.equals("TAHNRENCPRO")){
				mapParam.put("id_pltu", Registry.get("id_pltu").toString());
				mapParam.put("tahun", cboTahun.getRawValue().toString());
			}else{
				mapParam.put("id_pltu", Registry.get("idPltu").toString());
			}
		  
		  
//		  mapParam.put("id_unit", Registry.get("id_unit").toString());
  		  service.getListRencanaByKit(codectrl, mapParam,new AsyncCallback<List<Map>>() {
  			public void onFailure(Throwable caught) {
  				GWT.log(caught.getMessage(), null);  			  				
  			}

  			public void onSuccess(List<Map> result) {
  				if (codectrl.equals("LISTRENC")){
  	  				storePltu.removeAll();
  	  				storePltu.add(ClientModule.setListBaseModelFromListMap(result));
  	  				gridPltu.unmask();
  				}else if (codectrl.equals("RKAP")){
  	  				storeRkap.removeAll();
  	  				storeRkap.add(ClientModule.setListBaseModelFromListMap(result));
  	  				gridRkap.unmask();
  				}else if (codectrl.equals("TAHUNRENCPRO")){
  	  				storeRkap.removeAll();
  	  				storeRkap.add(ClientModule.setListBaseModelFromListMap(result));
  	  				gridRkap.unmask();	
  				}
  			}  			
  		});
		}
	}
	private void initStore(){
		  storePltu= new ListStore();
		  storeUraian= new ListStore();
		  storeTahun= new ListStore();
		  storeUnit= new ListStore();
		  storeBulan = new ListStore();
		  storeRkap = new GroupingStore();
	  }
	
	private Grid createGridPltu() {
		// TODO Auto-generated method stub
	    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

	    ColumnConfig column = new ColumnConfig();	    	     
	    
	    column = new ColumnConfig();  
	    column.setId("id_pltu");  
	    column.setHidden(true);
	    column.setWidth(1);    
	    configs.add(column);  


	    column = new ColumnConfig();  
	    column.setId("nama_pembangkit");  
	    column.setHeader("Pembangkit");    
	    column.setWidth(200);    
	    configs.add(column);  

	    column = new ColumnConfig();  
	    column.setId("jml_unit");  
	    column.setHeader("Jml Unit");  
	    column.setWidth(50);  
	    configs.add(column);  	  

//	    column = new ColumnConfig();  
//	    column.setId("tahun_akhir");  
//	    column.setHeader("Last Entry THN");  
//	    column.setWidth(100);  
//	    configs.add(column);  	  
//
//	    column = new ColumnConfig();  
//	    column.setId("bulan_akhir");  
//	    column.setHeader("Last Entry BLN");  
//	    column.setWidth(100);  
//	    configs.add(column);  	  
//	    
	    storePltu.setMonitorChanges(true);
	    
	    ColumnModel cm = new ColumnModel(configs);  
	  
	    gridPltu = new Grid(storePltu, cm);
	    gridPltu.setLoadMask(true);  
	    gridPltu.mask("load Data ...","x-mask-loading");
	    gridPltu.getView().setEmptyText("Data Empty");  
	    gridPltu.setBorders(false);  
	    gridPltu.setBorders(true);  
	    gridPltu.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge) {
            	try{
            		String id_pltu = gridPltu.getSelectionModel().getSelectedItem().get("id_pltu");
            		Registry.register("id_pltu", id_pltu);
            		namaPltu.setValue(gridPltu.getSelectionModel().getSelectedItem().get("nama_pembangkit"));
//                	MessageBox.alert("info", " test " + id_pltu , null);
            		
                	rkap("master","UNIT");
                	gridUraian.mask("load Data ...","x-mask-loading");
            		rkap("master","URAIAN");
            		gridRkap.mask("load Data ...","x-mask-loading");            		
            		rkap("rencana","RKAP");
            		
            		cboTahun.setEnabled(true);
            		noRkap.setValue("");
            		Map mapParam = new FastMap();
            		mapParam.put("tahun", fmt.format(today));
            		mapParam.put("id_pltu", id_pltu);
            		  service.getListRencanaByKit("TAHUNRENCPRO", mapParam,new AsyncCallback<List<Map>>() {
            	  			public void onFailure(Throwable caught) {
            	  				GWT.log(caught.getMessage(), null);  			  				
            	  			}

            	  			public void onSuccess(List<Map> result) {
//            	  					MessageBox.alert("info", "tahun " + result.get(0).get("tahun").toString() + " no rakp "  + result.get(0).get("no_rkap").toString() ,null);//            	  				
//            	  					noRkap.setValue(result.get(0).get("no_rkap").toString());	
//            	  	  				storeRkap.removeAll();
//            	  	  				storeRkap.add(ClientModule.setListBaseModelFromListMap(result));
//            	  	  				gridRkap.unmask();	
            	  					if (result.size() <= 0){
            	  						bNew.setEnabled(true);
				    	  				cboBulan.setEnabled(false);
//				    	  				cboTahun.setEnabled(true);
				    	  				btnTambah.setEnabled(false);		
				    	  				cboUnit.setEnabled(false);

            	  					}else{
            	  						MessageBox.alert("info", "Ditemukan Data RKAP <br> Tahun : " + result.get(0).get("tahun").toString() + " <br>NO RKAP : "  + result.get(0).get("no_rkap").toString() ,null);//            	  				
                	  					noRkap.setValue(result.get(0).get("no_rkap").toString());
                	  					cboTahun.setRawValue(result.get(0).get("tahun").toString());
                	  					bNew.setEnabled(false);
				    	  				cboBulan.setEnabled(true);
//				    	  				cboTahun.setEnabled(true);
				    	  				btnTambah.setEnabled(true);		
				    	  				cboUnit.setEnabled(true);

            	  					}		

            	  			}  			
            	  		});
            		
            	}catch (Exception e) {
					// TODO: handle exception
            		e.getMessage();
				}
            	
            	
            	
            }
		});

	  
	    return gridPltu;  
	}
	  private Grid createGridUraian() {
		// TODO Auto-generated method stub
		    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig();	    	     
		    
		    column = new ColumnConfig();  
		    column.setId("id_uraian");  
		    column.setHidden(true);
		    column.setWidth(1);    
		    configs.add(column);  


		    column = new ColumnConfig();  
		    column.setId("uraian");  
		    column.setHeader("Uraian");    
		    column.setWidth(180);    
		    configs.add(column);  

		    column = new ColumnConfig();  
		    column.setId("satuan");  
		    column.setHeader("Satuan");  
		    column.setWidth(150);  
		    configs.add(column);  	  

		    column = new ColumnConfig();  
		    column.setId("nilai");  
		    column.setHeader("Nilai");  
		    column.setWidth(150);
		    
		    TextField<String> text = new TextField<String>();  
		    text.setAllowBlank(false);  
		    column.setEditor(new CellEditor(text));  
		    configs.add(column);  		    		      	  

		    
		    storeUraian.setMonitorChanges(true);
		    
		    cm = new ColumnModel(configs);  
		  
		    gridUraian = new EditorGrid(storeUraian, cm);
//		    gridUraian.setLoadMask(true);  
//		    gridUraian.mask("load Data ...","x-mask-loading");
		    gridUraian.getView().setEmptyText("Data Empty");   
		    gridUraian.setBorders(true);
		    gridUraian.addListener(Events.AfterEdit, new Listener<BaseEvent>() {            
	            public void handleEvent(BaseEvent ge) {
	            	try{	            		
	            		String id = gridUraian.getSelectionModel().getSelectedItem().get("id_uraian").toString();
	            		String r = gridUraian.getSelectionModel().getSelectedItem().get("id_uraian").toString();
	            		String n = gridUraian.getSelectionModel().getSelectedItem().get("nilai").toString();
//	            		String dt = "0",cf = "0",jp = "0",sfc = "0"; 
//	            		gridUraian.getSelectionModel().getSelectedItem().get("id_uraian").toString();
	            			            	
//	            		gridUraian.
	            		
	            		if (r.equals("3")){
//	            			Registry.register("dt",n);	
	            			dt = n;
	            		}else if (r.equals("19")){
//	            			Registry.register("cf",n);
	            			cf = n;
	            		}else if (r.equals("22")){
//	            			Registry.register("jp",n);
	            			jp = n;
	            		}else if (r.equals("24")){
//	            			Registry.register("sfc",n);
	            			sfc = n;
//	            			MessageBox.alert("t", " dt " + Registry.get("dt") +" cf " + Registry.get("cf") + " jp " + Registry.get("cf") + " sfc " + Registry.get("sfc") + " totl batubara " + Integer.parseInt(Registry.get("dt").toString())*Integer.parseInt(Registry.get("cf").toString())*Integer.parseInt(Registry.get("jp").toString()), null);
	            		}
	            		
	            		
	            		
	            		
//	                	MessageBox.alert("tet","okkkk dt * cf "+ (Integer.parseInt(dt)*Integer.parseInt(cf)*Integer.parseInt(jp)*Integer.parseInt(sfc)),null);
	                	
	            	}catch (Exception e) {
						// TODO: handle exception
	            		e.getMessage();
					}
	            	
	            	
	            	
	            }
			});
//		    final String bgColor = "yellow";
//		     
//		    cm.setRenderer(new Renderer() {
//		     
//		       public String render(Object value,
//		          CellMetadata cellMetadata, Record record,
//		          int rowIndex, int colNum, Store store) {
//		     
//		              String htmlAttr = "style='background-color:" + bgColor + ";'";
//		              cellMetadata.setHtmlAttribute(htmlAttr);
//		     
//		              return (value != null ? value.toString() : null);
//		       }
//		    });
		  
		    return gridUraian;
	}
	private Grid createGridRkap() {
		// TODO Auto-generated method stub
		
		storeRkap.groupBy("unit");  
		
	    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

	    ColumnConfig column = new ColumnConfig();	        
		
	    	column = new ColumnConfig();  
	    	column.setId("id_unit");
	    	column.setHidden(true);
	    	column.setHeader("id_unit");
	    	column.setWidth(50);
			configs.add(column);  
		    
			column = new ColumnConfig();  
	    	column.setId("unit");
//	    	column.setHidden(true);
	    	column.setHeader("Unit");
	    	column.setWidth(50);
			configs.add(column); 
			
			column = new ColumnConfig();
			column.setId("id_uraian");
			column.setHeader("id_uraian");
		    column.setHidden(true);
		    column.setWidth(1);
			configs.add(column);

			column = new ColumnConfig();
			column.setId("uraian");
			column.setHeader("Uraian");
		    column.setWidth(180);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("satuan");
			column.setHeader("Satuan");
			column.setWidth(50);
			configs.add(column); 
			
			column = new ColumnConfig();
			column.setId("jan");
			column.setHeader("Januari");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column); 
			
			column = new ColumnConfig();
			column.setId("feb");
			column.setHeader("Februari");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("mar");
			column.setHeader("Maret");
		    column.setWidth(80);
		    column.setAlignment(HorizontalAlignment.RIGHT);
		    configs.add(column);
			
		    column = new ColumnConfig();
			column.setId("apr");
			column.setHeader("April");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);			
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("mei");
			column.setHeader("Mei");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("jun");
			column.setHeader("Juni");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("jul");
			column.setHeader("Juli");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("agt");
			column.setHeader("Agustus");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("sept");
			column.setHeader("September");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("okt");
			column.setHeader("Oktober");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("nop");
			column.setHeader("November");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			column = new ColumnConfig();
			column.setId("des");
			column.setHeader("Desember");
			column.setWidth(80);
			column.setAlignment(HorizontalAlignment.RIGHT);
			configs.add(column);
			
			storeRkap.setMonitorChanges(true);
		    
		    final ColumnModel cm = new ColumnModel(configs);  
		  
		    GroupingView view = new GroupingView();  
		    view.setShowGroupedColumn(false);  
//		    view.setForceFit(true);  
		    view.setGroupRenderer(new GridGroupRenderer() {  
			@Override
			public String render(GroupColumnData data) {
				// TODO Auto-generated method stub
				  String f = cm.getColumnById(data.field).getHeader();  
			        String l = data.models.size() == 1 ? "Item" : "Items";  
			        return f + ": " + data.group ; //+ " (" + data.models.size() + " " + l + ")";
			}  
		    });  
		    
		    
		    gridRkap = new Grid(storeRkap, cm);
		    gridRkap.setView(view);  
//		    gridRkap.setLoadMask(true);  
//		    gridRkap.mask("load Data ...","x-mask-loading");
		    gridRkap.getView().setEmptyText("Data Empty");  
		    gridRkap.setBorders(false);  
		    gridRkap.setBorders(true);  

	    return gridRkap;  
	  } 
	

}


